package com.example.finaltool.service;

import com.example.finaltool.annotations.Timer;
import com.example.finaltool.consts.Table;
import com.example.finaltool.mapper.MenuMapper;
import com.example.finaltool.model.DepInfo;
import com.example.finaltool.model.config.Data;
import com.example.finaltool.utils.PrintUtils;
import com.example.finaltool.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuService {

    MenuMapper mapper;

    @Autowired
    public MenuService(MenuMapper mapper) {
        this.mapper = mapper;
    }

    @Timer("系统菜单")
    @Transactional(rollbackFor = Exception.class)
    public void save(Data data, DepInfo info) {
        String corpId = data.getCorpId();

        // menu
        List<Long> menuExistSubIds = mapper.getMenuSubIds(corpId);
        if (info.getFuwu() != null) {
            if (CollectionUtils.isEmpty(menuExistSubIds) || !menuExistSubIds.contains(info.getFuwu())) {
                mapper.saveFuwuMenu(corpId, info.getFuwu());
            }
        }
        if (info.getXiangzhen() != null) {
            if (CollectionUtils.isEmpty(menuExistSubIds) || !menuExistSubIds.contains(info.getXiangzhen())) {
                mapper.saveGanbuMenu(corpId, info.getXiangzhen());
            }
        }
        notExist(info.cunIds(), menuExistSubIds).forEach(subId -> mapper.saveNonghuMenu(corpId, subId));

        // role
        List<Long> roleExistSubIds = mapper.getRoleSubIds(corpId);
        notExist(info.subIds(), roleExistSubIds).forEach(subId -> mapper.saveRole(corpId, subId));

        // role_menu
        List<Long> roleMenuExistSubIds = mapper.getRoleMenuSubIds(corpId);
        if (info.getFuwu() != null) {
            if (CollectionUtils.isEmpty(roleMenuExistSubIds) || !roleMenuExistSubIds.contains(info.getFuwu())) {
                mapper.saveFuwuRoleMenu(corpId, info.getFuwu());
            }
        }
        if (info.getXiangzhen() != null) {
            if (CollectionUtils.isEmpty(roleMenuExistSubIds) || !roleMenuExistSubIds.contains(info.getXiangzhen())) {
                mapper.saveGanbuRoleMenu(corpId, info.getXiangzhen());
            }
        }
        notExist(info.cunIds(), roleMenuExistSubIds).forEach(subId -> mapper.saveNonghuRoleMenu(corpId, subId));

        // sys_org
        if (CollectionUtils.isEmpty(mapper.getOrgSubIds(corpId))) {
            mapper.saveOrg(StringUtils.buildName(data), corpId);
        } else {
            PrintUtils.showExist(Table.SYS_ORG);
        }
    }

    private List<Long> notExist(List<Long> fromInfo, List<Long> fromDb) {
        List<Long> copy = new ArrayList<>(fromInfo);
        copy.removeAll(fromDb);
        return copy;
    }
}
